<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryRef" :inline="true" :model="queryParams" label-width="150px">
      <el-form-item label="商户名称" prop="commercialTenantName">
        <el-input
            v-model="queryParams.commercialTenantName"
            clearable
            placeholder="请输入商户名称"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户编号" prop="commercialTenantNo">
        <el-input
            v-model="queryParams.commercialTenantNo"
            clearable
            placeholder="请输入商户编号"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户手机号" prop="commercialTenantPhone">
        <el-input
            v-model="queryParams.commercialTenantPhone"
            clearable
            placeholder="请输入商户手机号"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商户类型" prop="commercialTenantState">
        <el-select v-model="queryParams.commercialTenantState" clearable
                   placeholder="请选择商户类型：1=普通商户,2=代理商户">
          <el-option
              v-for="dict in commercial_tenant_state"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="邮件" prop="commercialTenantEmil">
        <el-input
            v-model="queryParams.commercialTenantEmil"
            clearable
            placeholder="请输入邮件"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="贷记卡费率" prop="commercialCardpayFeeRate">
        <el-input
            v-model="queryParams.commercialCardpayFeeRate"
            clearable
            placeholder="请输入贷记卡费率(银行卡费率信息)"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="借记卡费率" prop="commercialCardpayDebitRate">
        <el-input
            v-model="queryParams.commercialCardpayDebitRate"
            clearable
            placeholder="请输入借记卡费率(银行卡费率信息)"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="封顶值" prop="commercialCardpayDebitCap">
        <el-input
            v-model="queryParams.commercialCardpayDebitCap"
            clearable
            placeholder="请输入封顶值(银行卡费率信息)"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="银联扫码优惠费率" prop="commercialPreferstageFeerate">
        <el-input
            v-model="queryParams.commercialPreferstageFeerate"
            clearable
            placeholder="请输入银联扫码优惠费率"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="微信费率" prop="commercialWxpayFeerate">
        <el-input
            v-model="queryParams.commercialWxpayFeerate"
            clearable
            placeholder="请输入微信费率"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="支付宝费率" prop="commercialAlipayFeerate">
        <el-input
            v-model="queryParams.commercialAlipayFeerate"
            clearable
            placeholder="请输入支付宝费率"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="外部商户" prop="outmerchantno">
        <el-input
            v-model="queryParams.outmerchantno"
            clearable
            placeholder="请输入外部商户"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="登录名称" prop="nickName">
        <el-input
            v-model="queryParams.nickName"
            clearable
            placeholder="请输入登录名称"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="最后登录IP" prop="loginIp">
        <el-input
            v-model="queryParams.loginIp"
            clearable
            placeholder="请输入最后登录IP"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button icon="Search" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['tenant:user:add']"
            icon="Plus"
            plain
            type="primary"
            @click="handleAdd"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            v-hasPermi="['tenant:user:export']"
            icon="Download"
            plain
            type="warning"
            @click="handleExport"
        >导出
        </el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="商户名称" prop="commercialTenantName" width="100"/>
      <el-table-column align="center" label="商户编号" prop="commercialTenantNo" width="100"/>
      <el-table-column align="center" label="商户手机号" prop="commercialTenantPhone" width="100"/>
      <el-table-column align="center" label="商户类型" prop="commercialTenantState" width="100">
        <template #default="scope">
          <dict-tag :options="commercial_tenant_state" :value="scope.row.commercialTenantState"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="邮件" prop="commercialTenantEmil" width="100"/>
      <el-table-column align="center" label="贷记卡费率" prop="commercialCardpayFeeRate" width="100"/>
      <el-table-column align="center" label="借记卡费率" prop="commercialCardpayDebitRate" width="100"/>
      <el-table-column align="center" label="封顶值" prop="commercialCardpayDebitCap" width="100"/>
      <el-table-column align="center" label="扫码优惠费率" prop="commercialPreferstageFeerate" width="120"/>
      <el-table-column align="center" label="微信费率" prop="commercialWxpayFeerate" width="100"/>
      <el-table-column align="center" label="支付宝费率" prop="commercialAlipayFeerate" width="100"/>
      <el-table-column align="center" label="外部商户号" prop="outmerchantno" width="100"/>
      <el-table-column align="center" label="商户状态" prop="status" width="100">
        <template #default="scope">
          <dict-tag :options="sys_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column align="center" label="登录名称" prop="nickName" width="100"/>
      <el-table-column align="center" label="最后登录IP" prop="loginIp" width="100"/>
      <el-table-column align="center" label="最后登录时间" prop="loginDate" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.loginDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作" width="400">
        <template #default="scope">
          <el-button
              v-hasPermi="['tenant:user:edit']"
              icon="message"
              type="text"
              @click="handleMeass(scope.row)"
          >
            详情
          </el-button>

        </template>

      </el-table-column>
    </el-table>

    <pagination
        v-show="total>0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <!-- 添加或修改商户对话框 -->
    <el-dialog v-model="open" :title="title" append-to-body width="500px">
      <el-form ref="userRef" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="商户名称" prop="commercialTenantName">
          <el-input v-model="form.commercialTenantName" placeholder="请输入商户名称"/>
        </el-form-item>
        <el-form-item label="商户手机号" prop="commercialTenantPhone">
          <el-input v-model="form.commercialTenantPhone" placeholder="请输入商户手机号"/>
        </el-form-item>

        <el-form-item label="商户类型">
          <el-radio-group v-model="form.commercialTenantState">
            <el-radio
                v-for="dict in commercial_tenant_state"
                :key="dict.value"
                :label="dict.value"
            >{{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="邮件" prop="commercialTenantEmil">
          <el-input v-model="form.commercialTenantEmil" placeholder="请输入邮件"/>
        </el-form-item>
        <el-form-item label="登录名称" prop="nickName">
          <el-input v-model="form.nickName" placeholder="请输入登录名称"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


    <!-- 添加或修改代理商对话框 -->
    <el-dialog v-model="agentOpen" :title="agentTitle" append-to-body width="500px">
      <el-form ref="agentRef" :model="agentform" :rules="agentRules" label-width="120px">
        <el-form-item label="手续费封顶值" prop="capValue">
          <el-input v-model="agentform.capValue" placeholder="请输入手续费封顶值"/>
        </el-form-item>
        <el-form-item label="报警值" prop="prewarningValue">
          <el-input v-model="agentform.prewarningValue" placeholder="请输入报警值"/>
        </el-form-item>
        <el-form-item label="手续费" prop="serviceCharge">
          <el-input v-model="agentform.serviceCharge" placeholder="请输入手续费"/>
        </el-form-item>
        <el-form-item label="已结手续费" prop="closedServiceCharge">
          <el-input v-model="agentform.closedServiceCharge" placeholder="请输入已结手续费"/>
        </el-form-item>
        <el-form-item label="手续费符号位" prop="serviceChargeSymbol">
          <el-input v-model="agentform.serviceChargeSymbol" placeholder="请输入手续费符号位"/>
        </el-form-item>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="agentSubmitForm">确 定</el-button>
          <el-button @click="agentCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script name="User" setup>
import {addUser, delUser, getUser, listUser, resetPwd, updateUser} from "@/api/tenant/user";
import {getCurrentInstance, reactive, ref, toRefs} from "vue";

const {proxy} = getCurrentInstance();
const {commercial_tenant_state, sys_status} = proxy.useDict('commercial_tenant_state', 'sys_status');

const userList = ref([]);
const open = ref(false);
const agentOpen = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const agentTitle = ref("");

const data = reactive({
  form: {},
  agentform: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    commercialTenantName: null,
    commercialSlat: null,
    commercialPassword: null,
    commercialTenantNo: null,
    commercialTenantPhone: null,
    commercialTenantParentId: null,
    commercialTenantState: null,
    commercialTenantEmil: null,
    commercialCardpayFeeRate: null,
    commercialCardpayDebitRate: null,
    commercialCardpayDebitCap: null,
    commercialPreferstageFeerate: null,
    commercialWxpayFeerate: null,
    commercialAlipayFeerate: null,
    outmerchantno: null,
    status: null,
    nickName: null,
    loginIp: null,
    loginDate: null,
  },
  rules: {
    commercialTenantName: [
      {required: true, message: "商户名称不能为空", trigger: "blur"}
    ],
    commercialSlat: [
      {required: true, message: "商户加密盐不能为空", trigger: "blur"}
    ],
    commercialPassword: [
      {required: true, message: "商户密码不能为空", trigger: "blur"}
    ],
    commercialTenantNo: [
      {required: true, message: "商户编号不能为空", trigger: "blur"}
    ],
    commercialTenantPhone: [
      {required: true, message: "商户手机号不能为空", trigger: "blur"}
    ],
    commercialTenantState: [
      {required: true, message: "商户类型：1=普通商户,2=代理商户不能为空", trigger: "blur"}
    ],
    commercialCardpayFeeRate: [
      {required: true, message: "贷记卡费率(银行卡费率信息)不能为空", trigger: "blur"}
    ],
    commercialCardpayDebitRate: [
      {required: true, message: "借记卡费率(银行卡费率信息)不能为空", trigger: "blur"}
    ],
    commercialCardpayDebitCap: [
      {required: true, message: "封顶值(银行卡费率信息)不能为空", trigger: "blur"}
    ],
    commercialPreferstageFeerate: [
      {required: true, message: "银联扫码优惠费率不能为空", trigger: "blur"}
    ],
    commercialWxpayFeerate: [
      {required: true, message: "微信费率不能为空", trigger: "blur"}
    ],
    commercialAlipayFeerate: [
      {required: true, message: "支付宝费率不能为空", trigger: "blur"}
    ],
  },
  agentRules: {
    capValue: [
      {required: true, message: "手续费封顶值不能为空", trigger: "blur"}
    ],
    prewarningValue: [
      {required: true, message: "报警值不能为空", trigger: "blur"}
    ],
    serviceCharge: [
      {required: true, message: "手续费不能为空", trigger: "blur"}
    ],
    closedServiceCharge: [
      {required: true, message: "已结手续费不能为空", trigger: "blur"}
    ],
    serviceChargeSymbol: [
      {required: true, message: "手续费符号位不能为空", trigger: "blur"}
    ],
  }
});

const {queryParams, form, rules, agentform, agentRules} = toRefs(data);

/** 查询商户列表 */
function getList() {
  loading.value = true;
  listUser(queryParams.value).then(response => {
    userList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    commercialTenantName: null,
    commercialSlat: null,
    commercialPassword: null,
    commercialTenantNo: null,
    commercialTenantPhone: null,
    commercialTenantParentId: null,
    commercialTenantState: "0",
    commercialTenantEmil: null,
    commercialCardpayFeeRate: null,
    commercialCardpayDebitRate: null,
    commercialCardpayDebitCap: null,
    commercialPreferstageFeerate: null,
    commercialWxpayFeerate: null,
    commercialAlipayFeerate: null,
    outmerchantno: null,
    status: "0",
    nickName: null,
    loginIp: null,
    loginDate: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    delFlag: null
  };
  proxy.resetForm("userRef");
}


// 表单重置
function agentReset() {
  agentform.value = {
    id: null,
    tenantId: null,
    parentIds: null,
    capValue: null,
    prewarningValue: null,
    serviceCharge: null,
    closedServiceCharge: null,
    serviceChargeSymbol: null,
  };
  proxy.resetForm("agentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}


/** 新增按钮操作 */
function handleAdd() {
  reset();
  proxy.$router.push({
    path: "/laiqianle/laiqianle/register/add",
  });
}


/** 详情 */
function handleMeass(row) {
  console.log(row)
  const _outMerchantNo = row.outmerchantno;
  // const _outMerchantNo = row.outMerchantNo;
  // proxy.$router.push(`spalice?id=${_id}&commercialTenantNo=${_commercialTenantNo}`);
  proxy.$router.push({
    path: "/spalice",
    query: {
      id: _outMerchantNo
    }
  });
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getUser(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改商户";
  });
}

/** 修改按钮操作 */
function handleUpAgent(row) {
  agentReset();
  agentform.value.tenantId = row.id;
  agentOpen.value = true;
  agentTitle.value = "升级代理商";
}


/** 代理商提交 */
function agentSubmitForm() {
  proxy.$refs["agentRef"].validate(valid => {
    if (valid) {
      addAgent(agentform.value).then(response => {
        proxy.$modal.msgSuccess("升级成功");
        agentOpen.value = false;
        getList();
      });
    }
  });
}

// 取消按钮
function agentCancel() {
  agentOpen.value = false;
  agentReset();
}

/**禁启用商户*/
function handleUpdateStatus(row, status) {
  reset();
  let updateStatus = {
    id: row.id,
    status
  };
  let title = "禁用"
  if (status === 1) {
    title = "启用";
  }
  proxy.$modal.confirm("是否" + title + row.commercialTenantName + "商户").then(function () {
    updateUser(updateStatus).then(function () {
      getList();
      proxy.$modal.msgSuccess(title + "成功");
    }).catch(() => {
      proxy.$modal.msgSuccess(title + "失败");
    });
  }).catch(() => {
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["userRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateUser(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addUser(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除商户编号为"' + _ids + '"的数据项？').then(function () {
    return delUser(_ids)
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('tenant/user/export', {
    ...queryParams.value
  }, `user_${new Date().getTime()}.xlsx`)
}


/** 重置密码按钮操作 */
function handleResetPwd(row) {
  proxy
      .$prompt('请输入"' + row.commercialTenantName + '"的新密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        inputPattern: /^.{5,20}$/,
        inputErrorMessage: '用户密码长度必须介于 5 和 20 之间',
      }).then(({value}) => {
    resetPwd(row.id, value).then((response) => {
      proxy.$modal.msgSuccess('修改成功，新密码是：' + value);
    });
  }).catch(() => {
  });
}

getList();
</script>
